// pages/Home-music/index.js
import {  getBanners, getSongMenu } from '../../service/topMusic_api'
import queryRect from '../../utils/query-rect'
import { throttle } from '../../utils/throttle'
import { rankingStore } from '../../store/index'
import { playerStore } from '../../store/index'
// 对查询函数进行节流
const throttleQueryRect = throttle(queryRect, 1000, {
  leading: true,
  trailing: true
})

const rankingMap = ['upRanking', 'newRanking', 'originRanking']

Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners: [],
    ImageHeight: null,
    recommedSongs: [],
    hotSongMenu: [],
    recommedMenu: [],
    rankings: [],

    isPlaying: false,
    playDetail: null,
    playAnimState: "paused"
  },

  /**
   * 处理轮播图height
   */
  handSwiperImageLoaded: function() {
    throttleQueryRect('.banner-image').then(res => {
      this.setData({ ImageHeight: res[0].height })
    })
  },

  // 处理页面跳转
  handleSearchClick: function() {
    wx.navigateTo({
      url: '/pages/detail-search/index',
    })
  },
  handleMoreHotSongClick: function() {
    return this.goNavigation(this.getRanking('热歌榜'), 'rank')
  },
  handleRankItemClick: function(event) {
    const rankName = event.currentTarget.dataset.item.name
    return this.goNavigation(this.getRanking(rankName), 'rank')
  },
  handleMenuDetailClick: function(event) {
    const id = event.currentTarget.dataset.item.id
    return this.goNavigation(id, 'menu')
  },
  goNavigation: function(info, type) {
    wx.navigateTo({
      url: `/pages/detail-menu/index?info=${info}&type=${type}`,
    })
  },
  getRanking: function(rankName) {
      switch(rankName) {
        case '热歌榜': {
          return 'hotRanking'
        }
        case '新歌榜': {
          return 'newRanking'
        }
        case '飙升榜': {
          return 'upRanking'
        }
        case '原创榜': {
          return 'originRanking'
        }
      }
  },
  handleSongItemClick: function(event) {
    const index = event.currentTarget.dataset.index
    playerStore.setState('playMusicIndex', index)
    playerStore.setState('playMusicList', this.data.recommedSongs)
  },
  handlePlayBtnClick: function(event) {
    playerStore.dispatch("changePlayingStatuAction", !this.data.isPlaying)
    // Propagation 繁殖
    // event.stopPropagation()
  },
  handlePlayBarClick: function() {
    wx.navigateTo({
      url: '/pages/music-player/index?id=' + this.data.playDetail.id,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    // 获取轮播图数据
    getBanners(2).then(res => {
      this.setData({ banners: res.banners })
    })

    // 获取榜单数据
    rankingStore.dispatch('getRankingData')
    // 获取推荐歌曲(热门榜单前六条数据)
    rankingStore.onState('hotRanking', res => {
      if (!res.tracks) return
      this.setData({ recommedSongs: res.tracks.slice(0, 6) })
    })
    // 获取当前播放歌曲信息
    playerStore.onStates(["playDetail", "isPlaying"], ({playDetail, isPlaying}) => {
      if (playDetail) this.setData({ playDetail })
      if (isPlaying !== undefined) {
        this.setData({ 
          isPlaying, 
          playAnimState: isPlaying ? "running": "paused" 
        })
      }
    })
    // 获取巅峰榜单列表（新歌榜，飙升榜，原创榜的前三条数据）
    for (let i = 0; i < rankingMap.length; i++) {
      rankingStore.onState(rankingMap[i], res => {
        if (Object.keys(res).length <= 0) return
        const name = res.name
        const imageUrl = res.coverImgUrl
        const playCount = res.playCount
        const tracks = res.tracks.slice(0, 3)
        const rankingObj = {name, imageUrl, tracks, playCount}
        const arr = [...this.data.rankings]
        arr.push(rankingObj)
        this.setData({ rankings: arr })
      })
    }

    // 获取热门歌单
    getSongMenu("全部", 6, 0).then(res => {
      this.setData({ hotSongMenu: res.playlists })
    })

    // 获取推荐歌单
    getSongMenu("华语", 6, 0).then(res => {
      this.setData({ recommedMenu: res.playlists })

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})